package com.brand.data.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * 加密工具类
 * @author scl
 *
 */
public class DigestUtil {
	private static MessageDigest md5;
	private final static String DES = "DES";
	private final static String CHARSET = "utf-8";
	private static SecretKeyFactory keyFactory;
	static{
		try {
	        md5 = MessageDigest.getInstance("MD5");
	        //des加密密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
	        keyFactory = SecretKeyFactory.getInstance(DES);
	    } catch (Exception e) {
	        e.printStackTrace();  
	    }
	}
	/**
	 * 16位MD5加密
	 * @param inStr
	 * @return
	 */
    public static String md5_16(String inStr) {
    	try {
			return md5(inStr).substring(8, 24);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
    /**
     * 32位MD5加密
     * @param inStr
     * @return
     */
    public static String md5(String inStr) {  
	    if ( StringUtils.isEmpty(inStr) ) {
	    	return null;
	    }
	    byte[] byteArray = null;
		try {
			byteArray = inStr.getBytes(CHARSET);
			StringBuilder hexValue = new StringBuilder();
			byte[] md5Bytes = md5.digest(byteArray);  
			for (int i = 0; i < md5Bytes.length; i++) {  
				int val = ((int) md5Bytes[i]) & 0xff;  
				if (val < 16)  
					hexValue.append("0");  
				hexValue.append(Integer.toHexString(val));  
			}
			return hexValue.toString();	
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;  
	}
	/**
     * des加密算法，根据键值进行加密
     * @param data 
     * @param key  加密键
     * @return
     * @throws Exception
     */
    public static String desEncrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(CHARSET), key.getBytes(CHARSET));
        return new BASE64Encoder().encode(bt);
    }
 
    /**
     * DES加密算法，根据键值进行解密
     * @param data
     * @param key  加密键
     * @return
     * @throws Exception
     */
    public static String desDecrypt(String data, String key) throws Exception {
        if (data == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf,key.getBytes(CHARSET));
        return new String(bt, CHARSET);
    }
    /**
     * Description 根据键值进行加密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        Cipher cipher = getCipher(key,Cipher.ENCRYPT_MODE);
        return cipher.doFinal(data);
    }
	private static Cipher getCipher(byte[] key,int mode) throws  Exception {
		// 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        //用密钥工厂把DESKeySpec转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密钥初始化Cipher对象
        cipher.init(mode, securekey, sr);
		return cipher;
	}
     
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
        return cipher.doFinal(data);
    }
    
    public static String hexSha2(String str) {
		MessageDigest messageDigest;
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
			str = Hex.encodeHexString(hash);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
		
	}
}
